<?php
namespace Home\Controller;

use Common\Controller\HomeController;

class CustomerController extends HomeController
{
    /**
     *客户列表信息
     * @author Mr.Alien
     * @return string
     */
    public function index($p =1)
    {
        I('get.name') && ($this->where['name'] = array('like','%'.I('get.name').'%'));
        I('get.phone') && ($this->where['phone'] = array('like','%'.I('get.phone').'%'));
        if(!$this->auth->check('系统管理',session('id'))){
        	$this->where['user_id'] = session('id');	
        }      
        parent::index($p);
    }

    /**
     *客户列表信息
     * @author Mr.Alien
     * @return string
     */
    public function add()
    {
        $template_name = M("Price")->where(array('user_id'=>session('id')))->field("distinct template_name as name")->select();
        $this->assign('template_name',$template_name);
        parent::add();
    }


    /**
     * 保存客户信息
     * @author Mr.Alien
     * @return string
     */
    public function save()
    {
        if(I('post.id')){
            $has = M('Customer')->where(array('id'=>array('neq',I('post.id')),'user_id'=>session('id'),'phone'=>I('post.phone')))->find();
            $has && $this->error('此号码已存在');
        }else{
            $has = M('Customer')->where(array('phone'=>I('post.phone')))->find();
            $has && $this->error('此号码已存在');
        }
        $data = I('post.');
        if($data['id']){
            $res = M(CONTROLLER_NAME)->save($data);
        }else{
            $data['user_id'] = session('id');
            $data['is_member'] = 1;
            $res = M(CONTROLLER_NAME)->add($data);
        }
        if($res === false){
            $this->error('保存失败');
        }else{
            $this->success('保存成功');
        }
    }

    /**
     * 根据手机号过去用户名
     * @author Mr.Alien
     * @return string
     */
    public function getName()
    {
        $phone = I('post.phone');
        $customer = M('Customer')->where(array('phone'=>$phone))->find();
        if($customer){
            $this->success($customer['name']);
        }else{
            $this->error();
        }
    }

     /**
     * 根据手机号过去用户名
     * @author Mr.Alien
     * @return string
     */
    public function getCustomer()
    {
        $phone = I('post.phone');
        $customer = M('Customer')->where(array('phone'=>$phone))->find();
        if($customer){
            $this->success($customer);
        }else{
            $this->error();
        }
    }

      /**
     * 根据手机号获取会员相关的价格模板
     * @author Mr.Alien
     * @return string
     */
    public function getTemplateName()
    {
        $phone = I('post.phone');
        $template_name = M('Customer')->where(array('phone'=>$phone,'user_id'=>session('id')))->getField('template_name');
        if($template_name){
            $this->success($template_name);
        }else{
            $this->error();
        }
    }
}